﻿using PagedList;
using PagedList.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GiaoTrinhEPU.Repositories.Repositories;
using GiaoTrinhEPU.Repositories.DataModels;
using GiaoTrinhEPU.Repositories;
using GiaoTrinhEPU.Repositories.Interfaces;
using GiaoTrinhEPU.Core.ActionResults;
using GiaoTrinhEPU.Core;

namespace GiaoTrinhEPU.Areas.Manager.Controllers
{
    public class WarehouseController : BaseController
    {
        /// <summary>
        /// Declare Warehouse Repository
        /// </summary>
        private WarehouseRepository wareHouseRepository;

        /// <summary>
        ///  Declare Session
        /// </summary>
        public static string SessionWarehouseSort = "SessionWarehouseSort";
        public static string SessionWarehouseSearch = "SessionWarehouseSearch";
        public static string SessionWarehouseSortOpt = "SessionWarehouseSortOpt";



        // GET: /Warehouse/
        /// <summary>
        /// Constructor that allow to create a Comment controller
        /// </summary>
        public WarehouseController()
            : base()
        {
            this.wareHouseRepository = new WarehouseRepository();
            ViewBag.SelectedMenuId = 25;
        }

        public ActionResult Index(int page = 1, int size = 25, String search = "", String opt = "", String sort = "")
        {
            ViewBag.Title = "Kho";
            // Stored Session
            
            Session[SessionWarehouseSort] = sort.Trim().Length > 0 ? sort.ToLower() : Session[SessionWarehouseSort];
            Session[SessionWarehouseSortOpt] = opt.Trim().Length > 0 ? opt.ToLower() : Session[SessionWarehouseSortOpt];

            var wareHouse = this.wareHouseRepository.ListWarehouses(false).ToList();

            // Search
            if (Session[SessionWarehouseSearch] != null)
            {
                ViewBag.Keyword = Session[SessionWarehouseSearch].ToString();

                wareHouse = wareHouse.Where(l => l.Name.ToUpper().Contains(ViewBag.Keyword.ToUpper())).ToList();

            }
            // Sort 
            ViewBag.SortNameOpt = "desc";
            if (Session[SessionWarehouseSort] != null)
            {
                switch (Session[SessionWarehouseSort].ToString())
                {
                    case "name":
                        wareHouse = Session[SessionWarehouseSortOpt].ToString().Equals("desc") ? wareHouse.OrderByDescending(s => s.Name).ToList() : wareHouse.OrderBy(s => s.Name).ToList();

                        Session[SessionWarehouseSort] = "name";
                        ViewBag.SortNameOpt = Sort.SetSortOrderOption(Session[SessionWarehouseSortOpt].ToString());
                        break;

                    default:
                        break;
                }
            }


            return View(wareHouse.ToPagedList(page, size));
        }
        /// <summary>
        /// Get
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Create()
        {
            return View();
        }
        /// <summary>
        /// create action with param
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Create(WarehouseModel model)
        {
            ViewBag.EnabledMenu = false;

            if (!ModelState.IsValid)
            {
                return View("Create");
            }
            else
            {
                if (this.wareHouseRepository.HasNameExisted(model.Name) == true)
                {
                    return View("Create").WithErrorMessage("Tên kho đã được sử dụng");
                }


                var wareHouse = new Warehouse();
                wareHouse.Id = (int)model.Id;
                wareHouse.Name = model.Name;
                wareHouse.Description = model.Description;

                this.wareHouseRepository.CreateWarehouse(wareHouse);
                // Returns view with successful message
                return RedirectToAction("Index").WithSuccessMessage("Đã tạo thành công kho mới"); ;
            }
        }
        /// <summary>
        ///  Edit action 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Edit(int id = 0)
        {
            ViewBag.EnabledMenu = false;

            var wareHouse = this.wareHouseRepository.GetWarehouseById(id);
            var wareHouseModel = new WarehouseModel(wareHouse);

            // population dropdow list


            return View(wareHouseModel);
        }
        /// <summary>
        ///  Edit action 
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(WarehouseModel model)
        {
            ViewBag.EnabledMenu = false;

            if (!ModelState.IsValid)
            {
                return View("Edit");
            }
            else
            {
                if (this.wareHouseRepository.HasNameDuplicated(model.Id, model.Name) == true)
                {
                    return View("Edit").WithErrorMessage("Tên kho đã được sử dụng");
                }

                var wareHouse = new Warehouse();

                wareHouse.Id = (int)model.Id;
                wareHouse.Name = model.Name;
                wareHouse.Description = model.Description;

                this.wareHouseRepository.UpdateWarehouse(wareHouse);

                return RedirectToAction("Index").WithSuccessMessage("Đã sửa thành công kho này");

            }
        }
        /// <summary>
        /// Delete action 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Delete(int id)
        {
            this.wareHouseRepository.DeleteWarehouse(id);
            return RedirectToAction("Index").WithSuccessMessage("Đã xóa thành công kho này"); ;
        }

        /// <summary>
        ///  Delete Multi
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DeleteMulti(int[] ids = null)
        {
            if (ids == null || ids.Length == 0)
            {
                return RedirectToAction("Index");
            }

            for (int i = 0; i < ids.Length; i++)
            {
                int id = ids[i];

                this.wareHouseRepository.DeleteWarehouse(id);
            }

            return RedirectToAction("Index").WithSuccessMessage("Đã xóa thành công những kho này");
        }
        /// <summary>
        /// Clear
        /// </summary>
        /// <returns></returns>
        public ActionResult Clear()
        {
            // Clear sessions
            Session[SessionWarehouseSearch] = null;
            Session[SessionWarehouseSort] = null;
            Session[SessionWarehouseSortOpt] = null;

            return RedirectToAction("Index");
        }
        /// <summary>
        /// check name avaiable
        /// </summary>
        /// <param name="name"></param>
        /// <param name="Id"></param>
        /// <returns></returns>
        public JsonResult IsNameAvaiable(String name, int Id = 0)
        {
            if (Id == 0)
            {
                if (!this.wareHouseRepository.HasNameExisted(name))
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            else
            {
                if (!this.wareHouseRepository.HasNameDuplicated(Id, name))
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }


            }

            return Json("Tên kho đã được sử dụng", JsonRequestBehavior.AllowGet);
        }
    }
}
